<template>
  <view class="coupon-popup" v-show="visible" @click.stop>
    <view class="close-btn" @tap="closePopup">
      <u-icon name="close" color="#FFFFFF" size="40"></u-icon>
    </view>
    <view class="coupon-content">
      <view class="content-box">
        <view class="info-row">
          <view class="info-label">
            <text>{{ genderInfo.firstUserTitle }}</text>
          </view>
          <view class="info-content">
            <view class="info-item">
              <text class="item-label">{{ genderInfo.firstUserName }}</text>
              <text class="item-value">{{ userInfo.surname + userInfo.name }}</text>
            </view>
            <view class="info-item">
              <text class="item-label">出生日期</text>
              <text class="item-value">{{ userInfo.birthText }}</text>
            </view>
          </view>
        </view>

        <!-- 修改这里为第二个用户信息的表单输入 -->
        <view class="info-row">
          <view class="info-label">
            <text>{{ genderInfo.secondUserTitle }}</text>
          </view>
          <view class="info-content form-area">
            <!-- 姓氏输入 -->
            <view class="form-item-inline">
              <view class="form-label">姓氏:</view>
              <view class="form-content">
                <u-input v-model="secondUser.surname" placeholder="请输入姓氏" class="form-input"
                  @input="validateChineseName('surname', secondUser.surname)" />
              </view>
            </view>

            <!-- 名字输入 -->
            <view class="form-item-inline">
              <view class="form-label">名字:</view>
              <view class="form-content">
                <u-input v-model="secondUser.name" placeholder="请输入名字" class="form-input"
                  @input="validateChineseName('name', secondUser.name)" />
              </view>
            </view>

            <!-- 生辰选择 -->
            <view class="form-item-inline">
              <view class="form-label">生辰:</view>
              <view class="form-content">
                <view class="birth-display" @tap="showDatePicker = true">
                  <text v-if="secondUser.birthText">{{ secondUser.birthText }}</text>
                  <text v-else class="placeholder">请选择出生日期</text>
                  <u-icon name="arrow-right" color="#999"></u-icon>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 价格信息 -->
        <view class="price-section">
          <view class="price-wrapper">
            <text class="original-price">原价￥{{ original }}</text>
            <text class="current-price">结缘价：{{ current }}元</text>
          </view>
        </view>
        <!-- 支付按钮 -->
        <view class="pay-button" @tap="createOrder">
          <text class="button-text">立即合婚</text>
        </view>
        <view class="pay-message">微信安全支付</view>
        <view class="user-count">已有 <span style="color:#dd302c">{{ Math.floor(userCount * 0.37) }}</span>人完成支付，获取了姻缘分析结果
        </view>

        <view class="otherComp-image">
          <image :src="feature.otherComp" mode="aspectFit"></image>
        </view>

        <view class="messageText">
          <text>支付后可立刻查看姻缘分析结果，本结果基于人工智能易学大模型LLM技术，后面保持不变。</text>
        </view>
      </view>

    </view>

    <!-- 日期选择器 -->
    <date-picker :show="showDatePicker" @close="showDatePicker = false" @cancel="showDatePicker = false"
      @confirm="handleDatePickerConfirm" />

    <!-- <pay-status-dialog :visible="showPayStatusDialog" @confirm="confirmPayment" @retry="createOrder" /> -->
  </view>
</template>

<script>
import { puthehunUserInfo, queryOrder } from '@/api/fortune';
import DatePicker from '@/components/date-picker';
// import PayStatusDialog from '@/components/dialog/PayStatusDialog.vue';
import { trackButton, trackPageView, trackPayment } from '@/utils/track';
import { mapActions, mapGetters } from 'vuex';

export default {
  name: 'HehunPopup',
  components: {
    DatePicker,
    // PayStatusDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      feature: {
        otherComp: "/static/images/payComp.png",
      },
      // 价格信息
      original: 129,
      current: 39.8,
      payMessages: {
        loading: "正在调起支付...",
        success: "支付成功",
        failure: "支付失败，请重试",
      },
      // 第二用户信息
      secondUser: {
        surname: '',
        name: '',
        gender: '',
        year: 0,
        month: 0,
        day: 0,
        hour: 0,
        minute: 0,
        birthText: '',
        sourceForm: 'test'
      },
      // 日期选择控制
      showDatePicker: false,
      showPayStatusDialog: false, // 支付状态弹窗
      currentorderNo: '', // 当前支付订单号
    };
  },
  computed: {
    ...mapGetters('system', ['userCount']),
    ...mapGetters('fortune', ['userInfo']),
    ...mapGetters('hehun', ['hehunUserInfo']),
    ...mapGetters('system', ['userId']),
    genderInfo() {
      if (this.userInfo.gender === '女')
        return {
          firstUserTitle: '女方信息',
          firstUserName: '女方姓名',
          secondUserTitle: '男方信息',
          secondUserName: '男方姓名',
          secondUserGender: '男',
          secondUserPrefix: '男',
        }
      else
        return {
          firstUserTitle: '男方信息',
          firstUserName: '男方姓名',
          secondUserTitle: '女方信息',
          secondUserName: '女方姓名',
          secondUserGender: '女',
          secondUserPrefix: '女',
        }
    }
  },
  watch: {
    visible(newVal) {
      // 当弹窗显示时，根据第一个用户的性别自动设置第二个用户的性别为相反的性别
      if (newVal) {
        this.secondUser.gender = this.genderInfo.secondUserGender;
        // 埋点：弹窗曝光
        trackPageView({
          reportKey: '进入合婚弹窗',
          reportVal: '浏览',
          pageName: '合婚弹窗'
        });
      }
    }
  },
  mounted() {
    // 初始化时设置第二个用户的性别为与第一个用户相反
    this.secondUser.gender = this.genderInfo.secondUserGender;
  },
  methods: {
    ...mapActions('hehun', ['setHehunUserInfo', 'setHehunUserId']),

    // 验证姓名只能输入汉字
    validateChineseName(field, value) {
      if (!value) return;
      const inputValue = field === 'surname' ? this.secondUser.surname : this.secondUser.name;
      const containsNonChinese = /[^\u4e00-\u9fa5]/.test(inputValue);
      if (containsNonChinese) {
        const filteredValue = inputValue.replace(/[^\u4e00-\u9fa5]/g, '');
        this.$nextTick(() => {
          if (field === 'surname') {
            this.secondUser.surname = filteredValue;
          } else {
            this.secondUser.name = filteredValue;
          }
        });
      }
    },
    // 处理日期选择器确认
    handleDatePickerConfirm({ year, month, day, hour, minute, birthText }) {
      // 直接使用解构赋值更新表单数据
      Object.assign(this.secondUser, { year, month, day, hour, minute, birthText });
    },
    // 外部调用：支付回跳后触发
    handlePaymentSuccess(orderNo) {
      this.currentorderNo = orderNo;
      this.secondUser = this.hehunUserInfo[1];
      this.confirmPayment();
    },
    // 处理支付
    async createOrder() {
      trackButton({
        reportKey: '立即合婚按钮',
        reportVal: '填写表单',
        pageName: '合婚弹窗'
      });
      // 1. 校验表单
      if (!this.secondUser.surname) {
        this.$show.showToast(`请输入${this.genderInfo.secondUserPrefix}方姓氏`);
        return;
      }
      if (!this.secondUser.name) {
        this.secondUser.name = this.genderInfo.secondUserGender === '男' ? '先生' : '女士';
      }
      if (!this.secondUser.birthText) {
        this.$show.showToast(`请选择${this.genderInfo.secondUserPrefix}方生辰`);
        return;
      }
      // 2. 构建下单参数
      const users = [
        { ...this.userInfo, userId: this.userId },
        { ...this.secondUser, userName: this.secondUser.surname + this.secondUser.name }
      ];
      // 存储合婚用户信息到 vuex
      await this.setHehunUserInfo(users);
      const orderParams = {
        goodsId: '20250618002', // 合婚商品ID（如有不同请调整）
        payAmount: 39, //this.current*100
        redirect: '/pages/payResult/result',
        type: 'hehun',
      };
      uni.showLoading({ title: '正在创建订单...', mask: true });
      this.$commonPay(orderParams);
      uni.hideLoading();
    },

    confirmPayment() {
      uni.showLoading({ title: '正在验证支付状态...', mask: true });
      this.verifyPaymentStatus(this.currentorderNo, async (success) => {
        uni.hideLoading();
        if (success) {
          // 支付验证成功
          try {
            const { data } = await puthehunUserInfo(this.hehunUserInfo);
            trackPayment({
              reportKey: '支付成功',
              reportVal: this.currentorderNo,
              pageName: '合婚弹窗'
            });
            this.$store.dispatch('payment/setPayStatus', { type: 'hehun', status: true });
            this.setHehunUserId(data);
            this.$show.showToast(this.payMessages.success, {
              icon: 'success',
              success: () => {
                this.$emit('confirm');
              }
            });
          } catch (error) {
            this.$show.showToast(error.message || '操作失败，请重试');
          }
        } else {
          // 支付验证失败
          // this.showPayStatusDialog = true;
          this.$show.showToast(this.payMessages.failure, { icon: 'error' });
          trackPayment({
            reportKey: '支付失败',
            reportVal: this.currentorderNo,
            pageName: '合婚弹窗'
          });
        }
      });
    },
    verifyPaymentStatus(orderNo, callback) {
      queryOrder(orderNo).then(res => {
        if (res.code === 0 && res.data && res.data.orderPayStatus === 1) {
          callback(true);
        } else {
          callback(false);
        }
      }).catch(err => {
        callback(false);
      });
    },
    closePopup() {
      this.$emit('close');
    },
  }
}
</script>

<style lang="scss" scoped>
@import "./popup.scss";

/* 添加表单样式 */
.form-area {
  width: 100%;
}

.form-item-inline {
  display: flex;
  flex-direction: row;
  width: 100%;
  align-items: center;
  margin-bottom: 15rpx;

  .form-label {
    width: 20%;
    font-size: 28rpx;
    color: #765244;
    font-weight: bold;
  }

  .form-content {
    width: 75%;
  }

  .form-input {
    width: 100%;
    height: 70rpx;
    border: 1px solid #ddd;
    border-radius: 10rpx;
    padding: 0 15rpx;
    font-size: 28rpx;
  }

  .birth-display {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 70rpx;
    border: 1px solid #ddd;
    border-radius: 10rpx;
    padding: 0 15rpx;
  }

  .placeholder {
    color: #999;
  }
}

.gender-select {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.gender-option {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-right: 30rpx;
}

.radio-button {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  border: 1px solid #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 8rpx;
  position: relative;
}

.radio-button.active {
  border-color: #4caf50;
  background-color: #4caf50;

  /* 添加勾选图标 */
  &:before {
    content: "";
    position: absolute;
    width: 14rpx;
    height: 7rpx;
    border-left: 2px solid white;
    border-bottom: 2px solid white;
    transform: rotate(-45deg);
    top: 9rpx;
    left: 7rpx;
  }
}
</style>